package org.idea.spring.framework.event.multiEvent.events;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.*;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 重写全局性事件异步发送组件
 *
 * @Author linhao
 * @Date created in 3:29 下午 2021/5/30
 */
@Configuration
public class MyEventPublishConfig implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        ApplicationEventMulticaster applicationEventMulticaster = applicationContext.getBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
        SimpleApplicationEventMulticaster simpleApplicationEventMulticaster = (SimpleApplicationEventMulticaster) applicationEventMulticaster;
        ExecutorService taskExecutor = Executors.newFixedThreadPool(10,new CustomizableThreadFactory("pool-idea-"));
        simpleApplicationEventMulticaster.setTaskExecutor(taskExecutor);
        simpleApplicationEventMulticaster.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {
            @Override
            public void onApplicationEvent(ContextClosedEvent event) {
                if (!taskExecutor.isShutdown()) {
                    taskExecutor.shutdown();
                    System.out.println("shutdown");
                }
            }
        });
    }
}
